
#include"Epoll.h"
#include"Channel.h"
#include"Socket.h"
void handleReadEvent(int fd)
{
    while(true)
    {
        char buff[BUFFER_NUM];
        bzero(buff,sizeof(buff));
        int read_bytes=read(fd,buff,sizeof(buff));
        if(read_bytes>0)
        {
            printf("the message from client is %s\n",buff);
            write(fd,buff,sizeof(buff));
        }
        else if(read_bytes==-1&&(errno==EAGAIN||errno==EWOULDBLOCK))
        {
            printf("finished read\n");
            break;
        }
        else if(read_bytes==-1&&errno==EINTR)
        {
            printf("interrupt error,continue!\n");
            continue;
        }
        else
        {
            printf("client fd: %d already closed!\n",fd);
            close(fd);
            break;
        }
    }
}

int main()
{
    Socket* serv_sock=new Socket();
    serv_sock->Bind();
    serv_sock->Listen();
    
    while(true)
    {
        int serv_fd=serv_sock->GetFd();
        Epoll* serv_epoll=new Epoll();
        //用ep做参数的channel添加
        Channel* serv_channel=new Channel(serv_epoll,serv_fd);
        serv_channel->enableRead();
        while(true)
        {
            std::vector<Channel*> retChannel=serv_epoll->poll();
            for(int i=0;i<retChannel.size();i++)
            {
                Channel* ChannelNode=retChannel[i];
                if(ChannelNode->getFd()==serv_fd)//新客户端连接
                {
                    int cli_fd=serv_sock->Accept();
                    Channel* cli_channel=new Channel(serv_epoll,cli_fd);
                    cli_channel->enableRead();
                }
                else if(ChannelNode->getRevents()&EPOLLIN)
                {
                    handleReadEvent(ChannelNode->getFd());
                }
                else
                {}
            }
        }
    }
    return 0; 
}



